package com.supinfo.food.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.supinfo.food.dao.TableDao;
import com.supinfo.food.entities.TableRestaurant;

/**
 * Table DAO
 * @author Keitaro
 */
public class JpaTableDao implements TableDao {

	/** Entity manager */
	private EntityManager entityManager;

	public JpaTableDao() {
		entityManager = ManagerDAO.getEntityManager();
	}
	
	@Override
	public TableRestaurant persist(TableRestaurant table) {
		entityManager.getTransaction().begin();
		entityManager.persist(table);
		entityManager.getTransaction().commit();
		return table;
	}

	@Override
	public TableRestaurant get(Long id) {
		try {
			return entityManager.find(TableRestaurant.class, id);
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public void remove(Long id) {
		TableRestaurant table = get(id);
		if (table != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(table);
			entityManager.getTransaction().commit();
		}
	}

	@Override
	public List<TableRestaurant> getByMagasin(Long id) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<TableRestaurant> query = cb.createQuery(TableRestaurant.class);
		Root<TableRestaurant> table = query.from(TableRestaurant.class);
		query.where(cb.equal(table.get("magasin").get("id"), id));
		try {
			return entityManager.createQuery(query).getResultList();
		} catch (NoResultException e) {
			return null;
		}
	}

}
